package com.winit.core.host.tailer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by keel2008 on 16/5/24.
 */
public class TailerContainer {

    static final Logger logger = LoggerFactory.getLogger(TailerContainer.class);

    static Map<String, Tailer4J> tailerMap = new HashMap<String, Tailer4J>();

    static Map<String, String> listenerKeyPathMapping = new HashMap<String, String>();

    static ExecutorService tailerCachedThreadPool = Executors.newFixedThreadPool(800);

    public void createNewTailer(String path, String listenerKey, Tailer4J.Listener listener) {
        logger.info("创建tailer,path="+path+",listenerKey="+listenerKey);

        stopTailer4J(path);

        Tailer4J tailer4J = new Tailer4J(path, listenerKey, listener);

        listenerKeyPathMapping.put(listenerKey, path);
        tailerMap.put(path,tailer4J);

        tailerCachedThreadPool.execute(tailer4J);

    }

    public void stopListener(String listenerKey) {
        String lKey = listenerKeyPathMapping.get(listenerKey);
        if (tailerMap.containsKey(lKey)) {
            this.tailerMap.get(lKey).removeListener(listenerKey);
        }
    }

    public void stopTailer4J(String path){
        if (tailerMap.containsKey(path)) {
            tailerMap.get(path).tailStop = Boolean.TRUE;
            tailerMap.remove(path);
        }
    }

//    public static void main(String[] args) throws Exception {
//
////        final TailerContainer tc = new TailerContainer();
//        Constants.TAILER_CONTAINER.createNewTailer("/Users/wangjian/Desktop/bbb", "token123123", new Tailer4J.Listener() {
//
//            @Override
//            public void onMessage(String msg,String filePath, String tokenId) {
//                System.out.println(msg);
//                if("stop".equals(msg)){
//                    Constants.TAILER_CONTAINER.stopTailer4J("/Users/wangjian/Desktop/bbb");
//                }
//            }
//
//            @Override
//            public Boolean isClosed() {
//                return Boolean.FALSE;
//            }
//        });
//
////        Thread.sleep(4000);
////
////        tc.stopListener("token123123");
//        while (true){
//            Thread.sleep(4000);
//            System.out.println(((ThreadPoolExecutor)tailerCachedThreadPool).getActiveCount());
//        }
//
//    }


}
